package com.qianwei.footpath.manage;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TimerManager {

    private static final String TAG = "TimerManager";

    private static TimerManager instance;
    private final List<TimerTask> timerTasks;
    private final Timer timer;

    private TimerManager() {
        timerTasks = new ArrayList<>();
        timer = new Timer();
    }

    public static synchronized TimerManager getInstance() {
        if (instance == null) {
            instance = new TimerManager();
        }
        return instance;
    }

    /**
     * @param delay    初始化时候间隔多久执行
     * @param interval 每多久回调一次
     * @param task     任务
     */
    public void startTimer(long delay, long interval, TimerTask task) {
        if (task != null) {
            timerTasks.add(task);
            timer.scheduleAtFixedRate(task, delay, interval);
        }
        Log.e(TAG, "现在任务数--------" + timerTasks.size());
    }

    public void stopTimer(TimerTask task) {
        if (task != null && timerTasks.contains(task)) {
            task.cancel();
            timerTasks.remove(task);
        }
        Log.e(TAG, "现在任务数--------" + timerTasks.size());
    }

    public void stopAllTimers() {
        for (TimerTask timerTask : timerTasks) {
            timerTask.cancel();
        }
        timerTasks.clear();
        Log.e(TAG, "现在任务数--------" + timerTasks.size());
    }

    public boolean isTimerRunning() {
        return !timerTasks.isEmpty();
    }
}
